package com.opo5.logisticsmanagement.common;

import com.opo5.logisticsmanagement.domain.AutoTask;
import com.opo5.logisticsmanagement.domain.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledFuture;

/**
 * @Title: AutoTaskUtil
 * @Author: lixin
 * @Date: 2022/07/11/13:49
 * @Description: 自动任务工具类
 */
@Slf4j
@Component
public class AutoTaskUtil {

    @Autowired
    public TaskScheduler taskScheduler;

    public ScheduledFuture start(AutoTask task) {

        //获取数据库数据
        String[] strArgs = null;
        String[] classTypes = null;
        if (task.getParam() != null && task.getParam().length()!=0) {
            //获取所有的参数
            strArgs = task.getParam().split(",");
        }
        //获取所有的方法名
        String methodName = task.getMethod();
        if (task.getParamType() != null && task.getParamType().length()!=0) {
            //获取所有的参数类型
            classTypes = task.getParamType().split(",");
        }


        List<Class<?>> argsTypeList = null;
        List<Object> argsList = null;

        if (strArgs != null && classTypes != null) {
            argsTypeList = new ArrayList<>();
            argsList = new ArrayList<>();
            for (int i = 0; i < strArgs.length; i++) {
                String classType = classTypes[i];
                if (classType.length() > 0) {
                    if ("string".equalsIgnoreCase(classType)) {
                        classType = "java.lang.String";
                        argsList.add(String.valueOf(strArgs[i]));
                    } else if ("integer".equalsIgnoreCase(classType) || "int".equalsIgnoreCase(classType)) {
                        classType = "java.lang.Integer";
                        argsList.add(Integer.valueOf(strArgs[i]));
                    } else if ("long".equalsIgnoreCase(classType)) {
                        classType = "java.lang.Long";
                        argsList.add(Long.valueOf(strArgs[i]));
                    } else if ("double".equalsIgnoreCase(classType)) {
                        classType = "java.lang.Double";
                        argsList.add(Double.valueOf(strArgs[i]));
                    } else if ("boolean".equalsIgnoreCase(classType)) {
                        classType = "java.lang.Boolean";
                        argsList.add(Boolean.valueOf(strArgs[i]));
                    }
                    try {
                        Class<?> aClass = Class.forName(classType);
                        argsTypeList.add(aClass);
                    } catch (ClassNotFoundException e) {
                        log.error("只支持基本的数据类型以及包装类，非法类型:{}", classType);
                    }
                }


            }
        }


        if (argsList!=null && argsTypeList!=null){
            // List转为Array，invoke要求
            Object[] args = new Object[argsList.size()];
            Class<?>[] classes = new Class[argsTypeList.size()];
            argsTypeList.toArray(classes);
            argsList.toArray(args);


            // 创建定时任务
            log.info("创建定时任务{}", task.getExpl());
            Runnable runnable = () -> {

                try {
                    Class<?> aClass = Class.forName(task.getReference());
                    Method method = aClass.getMethod(methodName, classes);
                    if (args.length > 0) {
                        method.invoke(aClass.newInstance(), args);
                    } else {
                        method.invoke(aClass.newInstance());
                    }

                } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                    log.error("定时任务{}执行完毕失败:{}", task, e.getMessage());
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                } catch (InstantiationException e) {
                    throw new RuntimeException(e);
                }
            };
            return taskScheduler.schedule(runnable, new CronTrigger(task.getCron()));
        }else{

            // 创建定时任务
            log.info("创建定时任务{}", task.getExpl());
            Runnable runnable = () -> {

                try {
                    Class<?> aClass = Class.forName(task.getReference());
                    Method method = aClass.getMethod(methodName);
                    method.invoke(aClass.newInstance());
                } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                    log.error("定时任务{}执行完毕失败:{}", task, e.getMessage());
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                } catch (InstantiationException e) {
                    throw new RuntimeException(e);
                }
            };
            return taskScheduler.schedule(runnable, new CronTrigger(task.getCron()));

        }

    }

    public static Message getMessage(String title){
        Message message = new Message();
        message.setTitle(title);
        message.setReleaseDate(new Date());
        message.setStatus("0");
        return message;
    }

    public static int CompareStringDate(String s){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = sdf.parse(s);
            return new Date().compareTo(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}
